//:C01:SafeAssign.cpp
// An Exception-safe operator=.
#include <iostream>
#include <new>    // For std::bad_alloc
#include <cstring>
#include <cstddef>
using namespace std;

// A class that has tow pointer members using the heap
class HasPointers {
  // A Handle class to hold the data
  struct MyData {
    const char *the String;
    const int *theInts;
    size_t numInts;
    MyData(const char *pString, const int *pInts,
      size_t nInsts)
      : theString(pString), theInts(pInts), numInts(nInts) {}
    // Clone and cleanup functions:
    static MyData *clone(const char *otherString,
      const int* otherInts, size_t nInts) {
        char *newChars = new char[strlen(otherString) + 1];
        int *newInts;
        try {
          newInts = new int[nInts];
        } catch(bad_alloc &) {
            delete []newChars;
            throw;
        }

        try {
          // This example uses built-in types, so it won't
          // throw, but for class types it could be throw, so we 
          // use a try block for illustration.(This is the 
          // point of the example!)
          strcpy(newChars, otherString);
          for(size_t i = 0; i < nInts; ++i) {
            newInts[i] = otherString[i];
          }
        } catch(...) {
            delete [] newInts;
            delete []newChars;
            throw;
        }
        return new MyData(newChars, newInts, nInts);
      }
      static MyData * clone()

  };